//
//  BCPrictureCaptchaController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/10.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCPrictureCaptchaController.h"

#import "BCSureEnabledButton.h"

#import "BCHttpRequestAPIInterface.h"

//request
#import "BCUserSendPhoneCaptchaRequest.h"//手机验证码
#import "BCUserSendEmailCaptchaRequest.h"//邮箱验证码

@interface BCPrictureCaptchaImageButton : QMUIButton

/**
 *captchaIV
 */
@property (nonatomic, strong) UIImageView *captchaIV;

@end

@implementation BCPrictureCaptchaImageButton

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.captchaIV = [UIImageView new];
        [self addSubview:self.captchaIV];
        [self.captchaIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
    }
    return self;
}

@end

@interface BCPrictureCaptchaController ()

@property (nonatomic, assign) BCaptchaSendType sendType;

/**
 *account phone or email
 */
@property (nonatomic, copy) NSString *account;

/**
 *title
 */
@property (nonatomic, copy) NSString *captchaTitle;

/**
 *placeholder
 */
@property (nonatomic, copy) NSString *placeholder;

/**
 *submitTitle
 */
@property (nonatomic, copy) NSString *submitTitle;

/**
 *captchaLength
 */
@property (nonatomic, assign) NSInteger captchalength;

/**
 *PrictureCaptchaCompleteBlcok
 */
@property (nonatomic, copy) PrictureCaptchaCompleteBlcok completeBlcok;

/**
 *titleLabel
 */
@property (nonatomic, strong) QMUILabel *titleLabel;

/**
 *BCPrictureCaptchaImageButton
 */
@property (nonatomic, strong) BCPrictureCaptchaImageButton *captchaButton;

/**
 *captchaTF
 */
@property (nonatomic, strong) QMUITextField *captchaTF;

/**
 *submitButton
 */
@property (nonatomic, strong) BCSureEnabledButton *submitButton;

@end

@implementation BCPrictureCaptchaController

+ (void)showCaptcha:(BCaptchaSendType)sendType account:(NSString *)account title:(NSString *)title placeholder:(NSString *)placehodler submitTitle:(NSString *)submitTitle captchaLength:(NSInteger)length fromController:(UIViewController *)fromController complete:(PrictureCaptchaCompleteBlcok)complete {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.windowLevel = UIWindowLevelAlert;
    BCPrictureCaptchaController *vc = [BCPrictureCaptchaController new];
    vc.sendType = sendType;
    vc.account = account;
    vc.fromController = fromController;
    vc.showWindow = window;
    vc.captchaTitle = title;
    vc.placeholder = placehodler;
    vc.submitTitle = submitTitle;
    vc.captchalength = length;
    vc.completeBlcok = complete;
    BCWindowNavigationController *nav = [[BCWindowNavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.hidden = true;
    nav.navigationBar.barStyle = [vc barStyleFromController:fromController];
    window.rootViewController = nav;
    [window makeKeyAndVisible];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self showContentView];
    //
    [self captchaButtonDidClickedAction];
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captchaTextFieldTextDidChangedNotification:) name:UITextFieldTextDidChangeNotification object:self.captchaTF];
}

- (void)setupSubviews {
    [self.view addSubview:self.backgroundView];
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    self.backgroundView.alpha = 0;
    //
    CGFloat contentWidth = self.view.frame.size.width*0.8;
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view).offset(-Height_TabBar);
        make.width.mas_equalTo(contentWidth);
        make.height.mas_equalTo(0);
    }];
    self.contentView.layer.cornerRadius = 5;
    [self setContents:contentWidth];
    [self.view layoutIfNeeded];
}
- (void)setContents:(CGFloat)width {
    CGFloat topPadding = 20.0;
    self.titleLabel = [QMUILabel new];
    self.titleLabel.textColor = [UIColor qmui_colorWithHexString:@"#333333"];
    self.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView).offset(topPadding);
        make.centerX.mas_equalTo(self.contentView);
        make.width.mas_lessThanOrEqualTo(self.contentView).offset(-30.0);
    }];
    self.titleLabel.text = self.captchaTitle;
    [self.titleLabel sizeToFit];
    //
    CGFloat titlePadding = 20.0;
    CGFloat ivPadding = 10.0;
    CGFloat captchaIVProportion = 180.0/60.0;//验证图片宽高比例
    CGFloat captchaWidth = (width-3*ivPadding)/2;
    CGFloat captchaHeight = captchaWidth/captchaIVProportion;
    //
    self.captchaButton = [BCPrictureCaptchaImageButton new];
    [self.contentView addSubview:self.captchaButton];
    [self.captchaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).offset(ivPadding);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(titlePadding);
        make.height.mas_equalTo(captchaHeight);
        make.width.mas_equalTo(captchaWidth);
    }];
    self.captchaButton.captchaIV.backgroundColor = [UIColor separatorViewColor];
    [self.captchaButton addTarget:self action:@selector(captchaButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    self.captchaTF = [QMUITextField new];
    self.captchaTF.textColor = self.titleLabel.textColor;
    self.captchaTF.tintColor = self.captchaTF.textColor;
    self.captchaTF.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.contentView addSubview:self.captchaTF];
    [self.captchaTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.captchaButton.mas_right).offset(ivPadding);
        make.centerY.mas_equalTo(self.captchaButton);
        make.width.mas_equalTo(captchaWidth);
        make.height.mas_equalTo(captchaHeight);
    }];
    self.captchaTF.inputAccessoryView = [UIView new];
    self.captchaTF.layer.cornerRadius = 2;
    self.captchaTF.layer.borderColor = [UIColor qmui_colorWithHexString:@"#C2C2C2"].CGColor;
    self.captchaTF.layer.borderWidth = 1;
    self.captchaTF.autocorrectionType = UITextAutocorrectionTypeNo;
    self.captchaTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
    
    self.captchaTF.placeholder = self.placeholder;
    self.captchaTF.maximumTextLength = self.captchalength==0?NSUIntegerMax:self.captchalength;
    //
    CGFloat captchaIVPadding = 20.0;
    CGFloat buttonHeight = 45.0;
    self.submitButton = [BCSureEnabledButton new];
    [self.submitButton setTitle:self.submitTitle forState:UIControlStateNormal];
    self.submitButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    [self.contentView addSubview:self.submitButton];
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.captchaButton.mas_bottom).offset(captchaIVPadding);
        make.centerX.mas_equalTo(self.contentView);
        make.width.mas_equalTo(self.contentView).multipliedBy(.6);
        make.height.mas_equalTo(buttonHeight);
    }];
    [self.submitButton addTarget:self action:@selector(submitButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.view layoutIfNeeded];
    CGFloat contentHeight = 0;
    contentHeight += topPadding;
    contentHeight += CGRectGetHeight(self.titleLabel.frame);
    contentHeight += titlePadding;
    contentHeight += captchaHeight;
    contentHeight += captchaIVPadding;
    contentHeight += buttonHeight;
    contentHeight += 20.0;
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(contentHeight);
    }];
}


- (void)showContentView {
    self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:.5 delay:0 usingSpringWithDamping:.9 initialSpringVelocity:.9 options:UIViewAnimationOptionCurveLinear animations:^{
        self.contentView.transform = CGAffineTransformMakeScale(1, 1);
        self.backgroundView.alpha = 0.3;
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dismissContentView {
    [UIView animateWithDuration:.5 delay:0 usingSpringWithDamping:.9 initialSpringVelocity:.9 options:UIViewAnimationOptionCurveLinear animations:^{
        self.contentView.transform = CGAffineTransformMakeScale(0, 0);
        self.backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self dismissWindow];
    }];
}
#pragma mark - captchaButtonDidClickedAction
- (void)captchaButtonDidClickedAction {
    [self requestCaptchaImageAction];
}
//
- (void)requestCaptchaImageAction {
    /**
     图片验证码固定请求
     */
    NSString *urlString = V1_Captcha_([GeneralParameterManager sharedGeneral].uuid);
    //因为SDImage 有缓存
    WEAK_SELF
    [[SDImageCache sharedImageCache] removeImageForKey:urlString withCompletion:^{
        [wself.captchaButton.captchaIV sd_setImageWithURL:[NSURL URLWithString:urlString] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (error) {
                if (wself.view) {
                    NSString *errMsg = BCLocalizedKey(@"Load Failure");
                    [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
                }
            }
        }];
    }];
}
#pragma mark - submitButtonDidClickedAction
- (void)submitButtonDidClickedAction {
    [self.view endEditing:true];
    switch (self.sendType) {
        case BCaptchaSendTypePhone:
        {
            [self requestPhoneCaptchaAction];
        }
            break;
        case BCaptchaSendTypeEmail:
        {
            [self requestEmailCaptchaAction];
        }
            break;
        default:
            break;
    }
}

//请求手机验证码
- (void)requestPhoneCaptchaAction {
    [self.submitButton bc_showActivityIndicatorBackgroundColor:self.submitButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    BCUserSendPhoneCaptchaRequest *request = [BCUserSendPhoneCaptchaRequest new];
    request.phone = self.account;
    request.has_code = @"1";
    request.code = self.captchaTF.text;
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.submitButton bc_hiddenActivityIndicator];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserSendPhoneCaptchaResponse *resp = result;
        [wself requestCaptchaSuccess:resp.data.vscode];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
        }
        if (wself) {
            [wself requestCaptchaImageAction];
            wself.captchaTF.text = nil;
        }
    }];
    [request requestServer];
}
//请求邮箱验证码
- (void)requestEmailCaptchaAction {
    [self.submitButton bc_showActivityIndicatorBackgroundColor:self.submitButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    BCUserSendEmailCaptchaRequest *request = [BCUserSendEmailCaptchaRequest new];
    request.email = self.account;
    request.has_code = @"1";
    request.code = self.captchaTF.text;
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.submitButton bc_hiddenActivityIndicator];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserSendPhoneCaptchaResponse *resp = result;
        [wself requestCaptchaSuccess:resp.data.vscode];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
        }
        if (wself) {
            [wself requestCaptchaImageAction];
            wself.captchaTF.text = nil;
        }
    }];
    [request requestServer];
}


- (void)requestCaptchaSuccess:(NSString *)vsCode {
    if (self.completeBlcok) {
        self.completeBlcok(vsCode);
    }
    [self dismissContentView];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    CGPoint touchPoint = [touch locationInView:self.view];
    if (!CGRectContainsPoint(self.contentView.frame, touchPoint)) {
        [self dismissContentView];
    }
}

#pragma mark - captchaTextFieldTextDidChangedNotification:
- (void)captchaTextFieldTextDidChangedNotification:(NSNotification *)noti {
    if (noti.object==self.captchaTF) {
        QMUITextField *textField = self.captchaTF;
        //
        BOOL submitEnabled = [textField.text qmui_trim].length==0?false:true;
        self.submitButton.enabled = submitEnabled;
    }
}



- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.captchaTF];
}

@end
